package it.garr.biometrics {
	import flash.net.NetConnection;
	import flash.net.Responder;

	import flash.utils.ByteArray;

	import flash.events.IOErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.events.SecurityErrorEvent;

	import mx.controls.Alert;
	import mx.collections.ArrayCollection;

	public class AuthenticationServer {
		private var gateway:NetConnection;

        // Authentication threshold. Should be contained in the server but for
        // testing purpose it is embedded in the client
        private var auth_threshold:Number = -0.1;

		// URL of the authentication server (fixed at compile time)
		private var server_address:String = CONFIG::AMF_URL;

	    public function AuthenticationServer () {
            gateway = new NetConnection();
			// Handling errors
            gateway.addEventListener(IOErrorEvent.IO_ERROR, onFault);
			gateway.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onFault);
            gateway.addEventListener(NetStatusEvent.NET_STATUS, onFault);
		}

		public function compute_score(wavData:ByteArray, identity:String):void {
            var responder:Responder = new Responder( onSuccess, onFault );
            gateway.connect(server_address);

			gateway.call("bioauth.compute_score", responder, wavData, identity);
		}

		public function getIdentities():ArrayCollection {
            // List of identities, that should be gotten from the server, but
            // are actually mocked in the client for testing purposes
			var identities:ArrayCollection = new ArrayCollection();
            var i:int;
            for(i = 1; i <= 30; i++) {
                identities.addItem(String(i));
            }
			return identities;
		}

        private function onFault( err:* ): void {
			Alert.show("Error during authentication: " + err.name + "(" + err.message + ")", "Error");
        }

        private function onSuccess(data:Object): void {
			if(data.score > auth_threshold) {
				Alert.show("Authentication succeeded.", "Login");
			} else {
				Alert.show("Authentication did not succeed.", "Login");
			}
        }
	}
}
